import hashlib

from django.core.paginator import Paginator
from django.db.models import Q
from django.http import *
from django.shortcuts import render

# Create your views here.1111
from user.models import User
from .models import Department


# def init(request:HttpRequest):
#     print("OK")
#     return render(request,"user/init.html")
#
#
# def getInit(request:HttpRequest):
#     users=User.objects.all()
#     print(users)
#     paginator = Paginator(users, 10)
#     cur_page = request.GET.get('page', 1)  # 得到默认的当前页
#     page = paginator.page(cur_page)
#     return render(request, 'user/init.html', locals())

def init(request: HttpRequest):
    return render(request, 'department/init.html')


def getInit(request: HttpRequest):
    # 表格要展现的数据
    query = request.GET.get("id")
    if not query:
        print('a')
        departments = Department.objects.all()
    else:
        print('b')
        departments = Department.objects.filter(title__contains=query)
    # 处理成LayUi官方文档的格式
    lis = []
    for department in departments:
        data = dict()
        data['id'] = department.id
        data['title'] = department.title
        data['master'] = department.master.nickname if department.master else None
        data['dep_info'] = department.dep_info
        data['created_time'] = department.created_time
        data['updated_time'] = department.updated_time
        data['parent'] = department.parent.title if department.parent else None
        # 格式化时间的格式
        lis.append(data)
        # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    department_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    departments = {"code": 0, "msg": "", "count": departments.count(), "data": department_info}
    return JsonResponse(departments)


def preAdd(request: HttpRequest):
    if request.method == "GET":
        users=User.objects.all()
        departments = Department.objects.all()
        return render(request, 'department/add_department.html', locals())
    elif request.method == "POST":
        title = request.POST['title']
        master_id = request.POST['user_id']
        dep_info = request.POST['dep_info']
        # dep_path = request.POST['dep_path']
        parent_id = request.POST['parent_id']
        if not title or not master_id:
            # messages.error('用户名或密码为空')
            return JsonResponse({'state':2})
        # password=hash_encrytion(password_1) 上线时再添加
        elif Department.objects.filter(title=title):
            return JsonResponse({'state': 0,"error":"部门名称已被占用"})
        add_user=request.session['user']
        parent=Department.objects.get(id=parent_id)
        department = Department.objects.create(
            title=title,
            master=User.objects.get(id=master_id),
            dep_info = dep_info,
            parent= parent,
            creator=request.session['user']

        )
        department.dep_path=f"{str(parent.dep_path)}/{str(department.id)}"
        department.save()
        return JsonResponse({'state': "1"})


def del_department(request:HttpRequest):
    did=request.POST['id']
    department=Department.objects.get(id=did)
    Department.objects.filter(dep_path__startswith=department.dep_path).delete()
    return JsonResponse({'state':"1"})


def department_info(request:HttpRequest):
    if request.method=="GET":
        return render(request,'department/department_info.html')
    elif request.method=="POST":
        departments=Department.objects.filter(dep_path__startswith=request.session['user.department'].dep_path)
        list_department=[]
        for department in departments:
            data = dict()
            data['deptId'] = department.id
            data['deptName'] = department.title
            data['master'] = department.master.nickname if department.master else None
            data['dep_info'] = department.dep_info
            data['created_time'] = department.created_time
            data['updated_time'] = department.updated_time
            data['deptParentId'] = department.parent.id if department.parent else 0
            # 格式化时间的格式
            list_department.append(data)
        return JsonResponse({"code":0,"data":list_department})



def edit(request:HttpRequest):
    if request.method == "GET":
        did=request.GET.get("id")
        try:
            users = User.objects.all()
            department=Department.objects.get(id=did)
            departments=Department.objects.all()
        except:
            return HttpResponseNotFound
        return render(request, 'department/edit_department.html', locals())
    elif request.method == "POST":
        did=request.POST['id']
        title = request.POST['title']
        master_id=request.POST['master_id']
        dep_info=request.POST['dep_info']
        if not title or not master_id:
            return JsonResponse({'state': 2})
        if Department.objects.filter(Q(title=title)&~Q(id=did)):
            return JsonResponse({'state': 0})
        try:
            department = Department.objects.get(id=did)
        except:
            return JsonResponse({'state': 3})
        department.title=title
        department.master=User.objects.get(id="master_id")
        department.dep_info=dep_info
        department.save()
        return JsonResponse({'state': "1"})


def detail(request:HttpRequest):
    if request.method == "GET":
        did = request.GET.get("id")
        try:
            department = Department.objects.get(id=did)
            users = User.objects.all()
        except:
            return HttpResponseNotFound
    return render(request, 'department/detail_department.html', locals())


def get_detail(request:HttpRequest):
    did=request.GET.get('id')
    return render(request, 'department/info_init.html',locals())


def get_info(request:HttpRequest):
    did = request.GET.get("id")
    try:
        dept=Department.objects.get(id=did)
        users = User.objects.filter(dept=dept)
    except:
        users = User.objects.filter(dept=request.session['user.department'])
    # 处理成LayUi官方文档的格式
    lis = []
    for user in users:
        data = dict()
        data['id'] = user.id
        data['user_name'] = user.user_name
        data['role'] = user.role.name if user.role else None
        data['department'] = user.dept.title if user.dept else None
        data['telephone'] = user.telephone
        data['nickname'] = user.nickname
        data['email'] = user.email
        data['sex'] = user.sex
        data['last_login'] = user.last_login
        # 格式化时间的格式
        lis.append(data)
        # 前台传来的页数
    page_index = request.GET.get('page')
    # 前台传来的一页显示多少条数据
    page_limit = request.GET.get('limit')
    # 分页器进行分配
    paginator = Paginator(lis, page_limit)
    # 前端传来页数的数据
    data = paginator.page(page_index)
    # 放在一个列表里
    user_info = [x for x in data]
    # students.count()总数据量，layui的table模块要接受的格式
    users = {"code": 0, "msg": "", "count": users.count(), "data": user_info}
    return JsonResponse(users)
